﻿using System.Globalization;
using Microsoft.Phone.Shell;
using Tfs.OnTheRoad.Model;
using System.Data.Services.Client;
using System;
using Tfs.OnTheRoad.Helpers;
using System.Windows;
using Tfs.OnTheRoad.ViewModel;
using Tfs.OnTheRoad.Controls;
namespace Tfs.OnTheRoad.Commands
{
    /// <summary>
    /// Navigates to WorkItems Details
    /// </summary>
    public class NavigateToWorkItemCommand : BaseCommand
    {
        public NavigateToWorkItemCommand() : base() { }
        public NavigateToWorkItemCommand(FindWorkItemPanel findWorkItemPanel) : base() 
        {
            _findWorkItemPanel = findWorkItemPanel;
        }
        private FindWorkItemPanel _findWorkItemPanel;
        public override void Execute(object parameter)
        {
            System.Windows.Controls.SelectionChangedEventArgs args = parameter as System.Windows.Controls.SelectionChangedEventArgs;
            if (args != null && args.AddedItems.Count > 0)
            {
                // Set the selected item as the current item.
                var currentWorkItem = args.AddedItems[0] as WorkItem;
                navigateToWorkItemDetails(currentWorkItem);
            }
            else if(args==null && parameter!=null)
            {
                //http://tfs.savcor.de/TFSCollectionName/WorkItems(id) 
                DataServiceCollection<WorkItem> findWorkItemRequest;
                var context = App.CreateTfsDataServiceContext();
                findWorkItemRequest = new DataServiceCollection<WorkItem>(context);
                findWorkItemRequest.LoadCompleted += new System.EventHandler<LoadCompletedEventArgs>(findWorkItemRequest_LoadCompleted);
                findWorkItemRequest.LoadAsync(new Uri(string.Format("WorkItems({0})",parameter), UriKind.Relative));
                if(_findWorkItemPanel!=null)
                    _findWorkItemPanel.Processing = true;
            }
        }

        private void navigateToWorkItemDetails(WorkItem currentWorkItem)
        {
            PhoneApplicationService.Current.State["CurrentWorkItem"] = currentWorkItem;
            // Navigate to the new page.
            NavigateTo(string.Format(CultureInfo.InvariantCulture, "/Pages/WorkItemDetailsPage.xaml?workItemId={0}", currentWorkItem.Id));
        }

        void findWorkItemRequest_LoadCompleted(object sender, LoadCompletedEventArgs e)
        {
            if (_findWorkItemPanel != null)
                _findWorkItemPanel.Processing = false;
            DataServiceCollection<WorkItem> foundWorkItems = sender as DataServiceCollection<WorkItem>;
            if (e.Cancelled)
            {
                MessageBox.Show("The operation has been cancelled","Go To Work Item",MessageBoxButton.OK);
            }
            else if (e.Error != null)
            {
                var message = e.Error.Message;
                Exception dataServiceException;
                if (!System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
                    message = "Unable to connect. Data/Wi-Fi connection not available.";
                else if (DataServiceExceptionHelper.TryParse(e.Error, out dataServiceException))
                {
                    message = dataServiceException.Message;
                }
                else if ((e.Error.InnerException != null) && !string.IsNullOrEmpty(e.Error.InnerException.Message))
                {
                    if (string.Compare(e.Error.InnerException.Message, "NotFound", StringComparison.OrdinalIgnoreCase) == 0)
                        message = string.Format("The address '{0}' could not be found.", App.SettingsViewModel.FullAddress);
                    else
                        message = e.Error.InnerException.Message;
                }
                MessageBox.Show(message, "Go To Work Item", MessageBoxButton.OK);
            }
            else if(foundWorkItems!=null)
            {
                if (foundWorkItems.Count == 0)
                    MessageBox.Show("No Work Item was found", "Go To Work Item", MessageBoxButton.OK);
                else
                    navigateToWorkItemDetails(foundWorkItems[0]);
            }
        }
    }
}